/*
 NAME: 
 DESCRIPTION: 上传matrix信息/存储profile信息
 PARAMETER:
	[
		{
			name:"step",
			title:"step名称",
			type:"LineEdit",
			property:{tool_tip:"step名称,默认orig"}
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
	
 VERSION_HISTORY:
	V1.00 2020-08-31 Scott Sun
		1.新版本
		
 HELP:
	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		  <p> template </p>
		  <br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		  <p> ● 无 </p>
	</body></html>
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>检查ol尺寸");



// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var _ = require('lodash');
var Error = require("topsin.error");

var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var Return = 'finish';
var resultData = [];

try {
	
	var par = PAR;
	var default_par = {
		step: "orig|array|set",
		auto_save: "No",
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	var step = par.step;
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	// 检查料号是否存在
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	// 检查料号是否被打开
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
	// 检查料号是否能够check out
	if(mode=="aimdfm"){
		if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
		GEN.checkInout({job:job,mode:"out"});
	}

	// jtg_unit_size_w jtg_unit_size_l
	// 获取dfm数据 pcs尺寸 交货形式 是否加工艺边
	var jtg_delivery_form_x = IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_delivery_form_x" }) // 交货形式
	var jtg_delivery_form_y = IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_delivery_form_y" }) // 交货形式
	var jtg_is_process_edge = IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_is_process_edge" })  // 是否加工艺边
	var jtg_unit_size_w = IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_unit_size_w" })
	var jtg_unit_size_l = IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_unit_size_l" })
	// if(!jtg_unit_size_w || jtg_unit_size_w == ""){
	// 	throw "dfm信息不存在"
	// }
	// if(!jtg_unit_size_l || jtg_unit_size_l == ""){
	// 	throw "dfm信息不存在"
	// }
	// var tmp = [jtg_unit_size_w - 0, jtg_unit_size_l - 0];

	// jtg_pcs_x0 jtg_pcs_y0   jtg_set_x jtg_set_y

	var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(v){
		var reg = new RegExp(par.step,"ig")
		return reg.test(v)
	})
	if(stepList.length == 0){throw "未找到step"}
	stepList.forEach(function(step){
		var profile = GEN.getProfileLimits({job:job, step:step, units:"mm"});  // {"xmin":"0","ymin":"0","xmax":"208.0001125","ymax":"173.000095","xsize":208.0001125,"ysize":173.000095}
		var tmp2 = [profile.xsize - 0, profile.ysize - 0];
		tmp2.sort();
		var tmp;		
		if(step == "orig"){
			if(/yes/ig.test(jtg_is_process_edge) && jtg_delivery_form_x != 1) {
				tmp = getTmp(IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_set_x" }),
				IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_set_y" }))
			} else {
				tmp = getTmp(jtg_unit_size_w,jtg_unit_size_l)
			}
		} else if (/array|set/ig.test(step) && /yes/ig.test(jtg_is_process_edge)) {
			tmp = getTmp(IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_set_x" }),
			IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_set_y" }))
		} else if (Number(jtg_delivery_form_x) > 1) {
			var num = getNum(step)
			tmp = getTmp(IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_pcs_x" + (num-1) }),
			IKM.get_jobinfo( { jobid: JobId, jobinfo: "jtg_pcs_y" + (num-1) }))
		} else {
			tmp = getTmp(jtg_unit_size_w,jtg_unit_size_l)
		}
		
		if(tmp && tmp.length){
			var res = []
			tmp2.forEach(function(size, i){
				var tmpsize = Math.abs(size - tmp[i])
				if (tmpsize > 1) {
					res.push((i==0? "短" : "长") + "边与dfm尺寸不符")
				}
			})
			if(res.length) {
				IKM.msg(step + " " + res.join(";"))
			} 
		}
	})
	
	
	








	if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	} else {
		if(GEN.STATUS.length == 0){
			return Return;
		}else{
			GUI.msgBox("error", "error", GEN.STATUS);
			return 'Error';
		}
	}
}catch (e) {	
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
	Status = 'error';
	resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function getTmp (x, y) {
	var tmp = [x - 0, y - 0];
	tmp.sort()
	return tmp
}

function getNum(step){
	return /(\d*)/ig.exec(step)[1]
}